package com.dome.user.exception;

import com.dome.client.config.exception.FeignException;
import com.dome.client.config.exception.ParamException;
import com.dome.client.config.exception.PublicException;
import com.dome.client.config.exception.ServerException;
import com.dome.client.config.result.RtnResult;
import com.dome.client.config.result.enums.RtnResultCodeEnums;
import com.netflix.hystrix.exception.HystrixRuntimeException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.List;

/**
 * 全局异常
 * @author hzhigg
 * 2018年12月14日
 */
@RestControllerAdvice(basePackages = {"com.dome.user.controller"})
public class GlobalExceptionHander {
    public static final Logger logger = LoggerFactory.getLogger(GlobalExceptionHander.class);

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public RtnResult handlerMethodArgumentException(MethodArgumentNotValidException e){
        BindingResult bindingResult = e.getBindingResult();
        StringBuffer errMes = new StringBuffer();
        if(bindingResult.hasErrors()){
            List<ObjectError> ls=bindingResult.getAllErrors();
            for (int i = 0; i < ls.size(); i++) {
                errMes.append("["+ls.get(i).getDefaultMessage()+"]");
            }
            logger.error("[参数异常]{}",errMes);
            return  RtnResult.Fail(errMes.toString());
        }else{
            logger.error("[系统异常]{}",e);
            return RtnResult.Fail();
        }
    }
    @ExceptionHandler(Exception.class)
    public RtnResult runtimeError(Exception e) {
        logger.error("[系统异常]{}",e.getMessage());
        e.printStackTrace();
        return RtnResult.Fail(RtnResultCodeEnums.FAIL);
    }
    
    @ExceptionHandler(ParamException.class)
    public RtnResult paramException(ParamException e) {
        logger.error("[参数异常]{}",e);
        return new RtnResult().Fail(e.toString());
    }
    
    @ExceptionHandler(ServerException.class)
    public RtnResult serverException(ServerException e) {
        logger.error("[运行异常]{}",e);
        return new RtnResult().Fail(e.getErrorMsg());
    }


    @ExceptionHandler(FeignException.class)
    public RtnResult feignException(FeignException e) {
        logger.error("[feign调用异常]{}",e.getMessage());
        e.printStackTrace();
        return new RtnResult().Fail(RtnResultCodeEnums.SERVICE_EXCEPTION.getMsgCN());
    }

    @ExceptionHandler(PublicException.class)
    public RtnResult publicException(PublicException e) {
        logger.error("[PublicException异常]{}",e.getErrorMsg());
        e.printStackTrace();
        return new RtnResult().Fail(e.getErrorMsg());
    }
}

